package com.haiertvbic.tvwa.network;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EncodingUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.haiertvbic.tvwa.util.SLog;

/**
 * 网络信息获取的相关类
 */
public class WebData {

	private static final String TAG = "WebData";

	public void name() {

	}

	/**
	 * 根据URL 获取网络数据
	 */
	void GetData(URL url) {
		try {
			// 模拟器测试时，请使用外网地址
			// URL url = new URL("http://xxx.xxx.xxx");
			URLConnection con = url.openConnection();

			String result = "http status code: ";
			// HttpURLConnection.HTTP_OK

			InputStream is = con.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			ByteArrayBuffer bab = new ByteArrayBuffer(32);
			int current = 0;
			while ((current = bis.read()) != -1) {
				bab.append((byte) current);
			}
			result += EncodingUtils.getString(bab.toByteArray(), HTTP.UTF_8);

			bis.close();
			is.close();

			// textView.setText(result);
		} catch (Exception e) {
			// textView.setText(e.toString());
		}
	}

	public String PostData(String url, Map<String, String> data) {
		try {
			// 模拟器测试时，请使用外网地址
			// post方法建立客户端和服务器端的连接
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			ArrayList<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
			for (Map.Entry<String, String> m : data.entrySet()) {
				postData.add(new BasicNameValuePair(m.getKey(), m.getValue()));
			}
			// 设置方法参数
			httpPost.setEntity(new UrlEncodedFormEntity(postData, HTTP.UTF_8));
			// 执行post方法
			HttpResponse response = httpClient.execute(httpPost);

			HttpEntity httpEntity = response.getEntity();
			// 获取响应数据
			InputStream is = httpEntity.getContent();
			String result = convertStreamToString(is);
			return result;
		} catch (Exception e) {
			System.out.println(e.toString());
			return null;
		}
	}

	/**
	 * 根据指定的URL和参数获取频道数据<br>
	 * 
	 * @param url
	 *            String<br>
	 * @param data
	 * <br>
	 * @return is InputStream<br>
	 */
	public InputStream PostDataStream(String url, Map<String, String> data) {

		try {
			// 模拟器测试时，请使用外网地址
			DefaultHttpClient httpClient = new DefaultHttpClient();
//			httpClient.getParams().setParameter("http.socket.timeout", 5000);
			HttpPost httpPost = new HttpPost(url);
			ArrayList<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
			for (Map.Entry<String, String> m : data.entrySet()) {
				postData.add(new BasicNameValuePair(m.getKey(), m.getValue()));
			}
			httpPost.setEntity(new UrlEncodedFormEntity(postData, HTTP.UTF_8));
			HttpResponse response = httpClient.execute(httpPost);
			// 测试连接情况
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200)
				throw new Exception("资源不存在!");
			SLog.d(TAG, "zhuang tai ma " + statusCode);

			HttpEntity httpEntity = response.getEntity();
			InputStream is = httpEntity.getContent();
			return is;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 判断网络连接是否可用
	 * 
	 * @returns
	 */
	public boolean getNetworkInfo(Context context) {
		ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = manager.getActiveNetworkInfo();
		if (info != null) {
			return info.isConnected();
		} else {
			return false;
		}

	}

	/**
	 * 把流转换为字符串。<br>
	 * 
	 * @param is
	 *            InputStream<br>
	 * @return str String<br>
	 */
	private String convertStreamToString(InputStream is) {
		// 字节流-->字符流
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			// 一行一行读取数据
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return sb.toString();
	}

}
